/*
 * File Name：CWDialog.java
 * Copyright：Copyright 2008 - 2012 CiWong.Inc. All Rights Reserved.
 * Description： CWDialog.java
 * Modify By：jejun
 * Modify Date：2012-10-28
 * Modify Type：Add
 */
package com.ciwong.mobilelib.widget;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.text.method.LinkMovementMethod;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckedTextView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ciwong.libs.utils.CWResource;
import com.ciwong.libs.utils.DeviceUtils;
import com.ciwong.mobilelib.utils.BaseConstants;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static android.view.WindowManager.LayoutParams.FIRST_SUB_WINDOW;
import static android.view.WindowManager.LayoutParams.LAST_APPLICATION_WINDOW;

/**
 * <pre>
 * </pre>
 *
 * @author jejun
 * @version ciwong v.1.0 2012-10-28
 * @since ciwong v.1.0
 */
public class CWDialog extends Dialog {

    protected Context mContext;

    private CWDialog base;

    private ViewGroup contentView;

    private ListView mListView;

    private ViewGroup mContainer;

    private boolean isTrans;

    private boolean useCommonCol = true;

    private final int rgb = 93;

    private final int textSize = BaseConstants.DIALOG_MESSAGE_TEXTSIZE;


    /**
     * 构造函数
     *
     * @param context 上下文
     */
    public CWDialog(Context context) {
        this(context, false);
    }


    /**
     * 构造函数
     *
     * @param context   上下文
     * @param isTransBg 是否是透明背景
     */
    public CWDialog(Context context, boolean isTransBg) {
        this(context, isTransBg, true);
    }

    /**
     * 构造函数
     *
     * @param context      上下文
     * @param isTransBg    是否是透明背景
     * @param useCommColor 是否用通用颜色
     */
    public CWDialog(Context context, boolean isTransBg, boolean useCommColor) {
        super(context, CWResource.getStyles("libs_cw_dialog"));
        mContext = context;
        contentView = (ViewGroup) LayoutInflater.from(context).inflate(CWResource.getLayout("libs_cw_dialog"), null);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);

        super.setContentView(contentView);
        setCanceledOnTouchOutside(false);
        base = this;
        isTrans = isTransBg;
        this.useCommonCol = useCommColor;
        if (isTransBg) {
            final int dipValue = 40;
            contentView.setBackgroundDrawable(CWResource.getDrawable("cw_dialog_trans"));
            contentView.findViewById(CWResource.getId("cw_dialog_title_container")).setBackgroundColor(Color.TRANSPARENT);
            contentView.findViewById(CWResource.getId("cw_dialog_content_container")).setBackgroundColor(Color.TRANSPARENT);
            RelativeLayout layout = (RelativeLayout) contentView.findViewById(CWResource.getId("cw_dialog_title_container"));
            layout.setMinimumHeight(DeviceUtils.dip2px(dipValue));
            Button btnOk = (Button) contentView.findViewById(CWResource.getId("cw_dialog_button_ok"));
            Button btnCan = (Button) contentView.findViewById(CWResource.getId("cw_dialog_button_neutral"));
            btnOk.setBackgroundDrawable(CWResource.getDrawable("dialog_btn"));
            btnCan.setBackgroundDrawable(CWResource.getDrawable("chat_send_button"));
            btnOk.setTextColor(Color.WHITE);
            // LayoutParams params = layout.getLayoutParams();
            // params.height =
            // ((TextView)contentView.findViewById(R.id.cw_dialog_title)).setTextColor(Color.WHITE);
            // ((TextView)contentView.findViewById(R.id.cw_dialog_title)).setTextColor(Color.WHITE);

        }
    }

    /**
     * 取消按钮
     *
     * @param text        按钮提示
     * @param listener    事件监听
     * @param autoDismiss 是否自动隐藏对话框
     * @return {@link CWDialog}
     */
    public CWDialog setNegativeButton(CharSequence text, final OnClickListener listener, final boolean autoDismiss) {
        Button negatvie = (Button) contentView.findViewById(CWResource.getId("cw_dialog_button_cancel"));

        negatvie.setText(text);
        if (useCommonCol) {
            negatvie.setTextColor(Color.rgb(rgb, rgb, rgb));
        }
        negatvie.setTextSize(textSize);

        negatvie.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (listener != null) {
                    listener.onClick(base, DialogInterface.BUTTON_NEGATIVE);
                }
                if (autoDismiss) {
                    base.dismiss();
                }
            }
        });
        negatvie.setVisibility(View.VISIBLE);
        ViewGroup buttonContainer = (ViewGroup) contentView.findViewById(CWResource.getId("cw_dialog_button_container"));
        buttonContainer.setVisibility(View.VISIBLE);
        return this;
    }

    /**
     * 取消按钮
     *
     * @param text        按钮提示
     * @param listener    事件监听
     * @param autoDismiss 是否自动隐藏对话框
     * @return {@link CWDialog}
     */
    public CWDialog setSingleButton(CharSequence text, final OnClickListener listener, final boolean autoDismiss) {
        Button negatvie = (Button) contentView.findViewById(CWResource.getId("cw_dialog_button_floor"));

        negatvie.setText(text);
        if (useCommonCol) {
            negatvie.setTextColor(Color.rgb(rgb, rgb, rgb));
        }
        negatvie.setTextSize(textSize);

        negatvie.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (listener != null) {
                    listener.onClick(base, DialogInterface.BUTTON_NEGATIVE);
                }
                if (autoDismiss) {
                    base.dismiss();
                }
            }
        });
        negatvie.setVisibility(View.VISIBLE);
        ViewGroup buttonContainer = (ViewGroup) contentView.findViewById(CWResource.getId("cw_dialog_button_container"));
        buttonContainer.setVisibility(View.VISIBLE);
        return this;
    }

    /**
     * 取消按钮
     *
     * @param text     按钮提示
     * @param listener 事件监听
     * @return this
     */
    public CWDialog setNegativeButton(CharSequence text, final OnClickListener listener) {
        return setNegativeButton(text, listener, true);
    }

    /**
     * 取消按钮
     *
     * @param resId       按钮提示字符串资料ID
     * @param listener    事件监听
     * @param autoDismiss 是否自动隐藏
     * @return this
     */
    public CWDialog setNegativeButton(int resId, final OnClickListener listener, boolean autoDismiss) {
        return setNegativeButton(mContext.getResources().getString(resId), listener, autoDismiss);
    }

    /**
     * 设置内容主体的高
     *
     * @param lp 布局参数
     * @return {@link CWDialog}
     */
    public CWDialog setMsgContentLayout(ViewGroup.LayoutParams lp) {
        if (mContainer == null) {
            mContainer = (ViewGroup) contentView.findViewById(CWResource.getId("cw_dialog_container"));
        }
        mContainer.setLayoutParams(lp);
        return this;
    }

    /**
     * 设置内容主体的高
     *
     * @param height 高
     * @return {@link CWDialog}
     */
    public CWDialog setMsgContentHeight(int height) {
        if (mContainer == null) {
            mContainer = (ViewGroup) contentView.findViewById(CWResource.getId("cw_dialog_container"));
        }
        ViewGroup.LayoutParams lp = mContainer.getLayoutParams();
        lp.height = height;
        setMsgContentLayout(lp);
        return this;
    }

    /**
     * 设置内容主体的宽
     *
     * @param width 宽
     * @return {@link CWDialog}
     */
    public CWDialog setMsgContentWidth(int width) {
        if (mContainer == null) {
            mContainer = (ViewGroup) contentView.findViewById(CWResource.getId("cw_dialog_container"));
        }
        ViewGroup.LayoutParams lp = mContainer.getLayoutParams();
        lp.width = width;
        setMsgContentLayout(lp);
        return this;
    }

    /**
     * 设置自定义布局<br />
     * <b style="color:red">调用此方法后,弹窗内的所有事件都由调用者处理,此时Dialog只作显示</b>
     *
     * @param layoutId 自定义布局资源ID
     * @return {@link CWDialog}
     */
    public CWDialog setCustomDialog(int layoutId) {
        return setCustomDialog(LayoutInflater.from(mContext).inflate(layoutId, null));
    }

    /**
     * 设置自定义布局<br />
     * <b style="color:red">调用此方法后,弹窗内的所有事件都由调用者处理,此时Dialog只作显示</b>
     *
     * @param customView 自定义布局
     * @return {@link CWDialog}
     */
    public CWDialog setCustomDialog(View customView) {
        contentView.removeAllViews();
        contentView.addView(customView);
        return this;
    }

    /**
     * 取消按钮
     *
     * @param resId    按钮提示字符串资料ID
     * @param listener 事件监听
     * @return this
     */
    public CWDialog setNegativeButton(int resId, final OnClickListener listener) {
        return setNegativeButton(mContext.getResources().getString(resId), listener, true);
    }

    public CWDialog setNegativeButtonTextColor(int resIdColor) {
        Button negatvie = (Button) contentView.findViewById(CWResource.getId("cw_dialog_button_cancel"));
        if (mContext != null) {
            negatvie.setTextColor(mContext.getResources().getColor(resIdColor));
        }

        return this;
    }

    /**
     * 确认按钮
     *
     * @param text        按钮提示
     * @param listener    事件监听
     * @param autoDismiss 是否自动隐藏对话框
     * @return {@link CWDialog}
     */
    public CWDialog setPositiveButton(CharSequence text, final OnClickListener listener, final boolean autoDismiss) {
        return setPositiveButton(text, listener, autoDismiss, null);
    }

    /**
     * 确认按钮
     *
     * @param text        按钮提示
     * @param listener    事件监听
     * @param autoDismiss 是否自动隐藏对话框
     * @param background  背景图资源
     * @return {@link CWDialog}
     */
    public CWDialog setPositiveButton(CharSequence text, final OnClickListener listener, final boolean autoDismiss, Drawable background) {
        Button positive = (Button) contentView.findViewById(CWResource.getId("cw_dialog_button_ok"));
        if (background != null) {
            final int paddingt = 10;
            final int paddingl = 20;
            positive.setBackgroundDrawable(background);
            positive.setPadding(paddingt, paddingl, paddingt, paddingl);
        }
        positive.setText(text);
        if (useCommonCol) {
            if (!isTrans) {
                positive.setTextColor(Color.rgb(rgb, rgb, rgb));
            }
        }
        positive.setTextSize(textSize);
        positive.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (listener != null)
                    listener.onClick(base, DialogInterface.BUTTON_POSITIVE);
                {
                }
                if (autoDismiss) {
                    base.dismiss();
                }
            }
        });
        positive.setVisibility(View.VISIBLE);
        ViewGroup buttonContainer = (ViewGroup) contentView.findViewById(CWResource.getId("cw_dialog_button_container"));
        buttonContainer.setVisibility(View.VISIBLE);
        return this;
    }

    /**
     * Ok按钮
     *
     * @param text
     * @param listener
     * @return
     */
    public CWDialog setOkButton(CharSequence text, final OnClickListener listener, Drawable background) {
        Button positive = (Button) contentView.findViewById(CWResource.getId("cw_dialog_button_ok"));
        final int paddingt = 10;
        final int paddingl = 20;
        positive.setBackgroundDrawable(background);
        positive.setPadding(paddingt, paddingl, paddingt, paddingl);
        positive.setText(text);
        positive.setTextColor(Color.WHITE);
        positive.setTextSize(textSize);
        positive.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (listener != null)
                    listener.onClick(base, DialogInterface.BUTTON_POSITIVE);
                {
                }
                base.dismiss();
            }
        });
        positive.setVisibility(View.VISIBLE);
        ViewGroup buttonContainer = (ViewGroup) contentView.findViewById(CWResource.getId("cw_dialog_button_container"));
        buttonContainer.setVisibility(View.VISIBLE);
        return this;
    }

    /**
     * 确认按钮
     *
     * @param text     按钮提示
     * @param listener 事件监听
     * @return {@link CWDialog}
     */
    public CWDialog setPositiveButton(CharSequence text, final OnClickListener listener) {
        return setPositiveButton(text, listener, true);
    }

    /**
     * Set a listener to be invoked when the neutral button of the dialog is
     * pressed.
     *
     * @param text        The text to display in the neutral button
     * @param listener    The {@link OnClickListener} to use.
     * @param autoDismiss 是否自动隐藏对话框
     * @return This Builder object to allow for chaining of calls to set methods
     */
    public CWDialog setNeutralButton(CharSequence text, final OnClickListener listener, final boolean autoDismiss) {
        Button neutral = (Button) contentView.findViewById(CWResource.getId("cw_dialog_button_neutral"));
        neutral.setText(text);
        if (useCommonCol) {
            neutral.setTextColor(Color.rgb(rgb, rgb, rgb));
        }
        neutral.setTextSize(textSize);
        neutral.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (listener != null) {
                    listener.onClick(base, DialogInterface.BUTTON_NEGATIVE);
                }
                if (autoDismiss) {
                    base.dismiss();
                }
            }
        });
        neutral.setVisibility(View.VISIBLE);
        ViewGroup buttonContainer = (ViewGroup) contentView.findViewById(CWResource.getId("cw_dialog_button_container"));
        buttonContainer.setVisibility(View.VISIBLE);
        return this;
    }

    /**
     * Set a listener to be invoked when the neutral button of the dialog is
     * pressed.
     *
     * @param text     The text to display in the neutral button
     * @param listener The {@link OnClickListener} to use.
     * @return This Builder object to allow for chaining of calls to set methods
     */
    public CWDialog setNeutralButton(CharSequence text, final OnClickListener listener) {
        return setNeutralButton(text, listener, true);
    }

    /**
     * Set a listener to be invoked when the neutral button of the dialog is
     * pressed.
     *
     * @param resId       The resource id of the text to display in the neutral button
     * @param listener    The {@link OnClickListener} to use.
     * @param autoDismiss 是否自动隐藏对话框
     * @return This Builder object to allow for chaining of calls to set methods
     */
    public CWDialog setNeutralButton(int resId, final OnClickListener listener, boolean autoDismiss) {
        return setNeutralButton(mContext.getResources().getString(resId), listener, autoDismiss);
    }

    /**
     * Set a listener to be invoked when the neutral button of the dialog is
     * pressed.
     *
     * @param resId    The resource id of the text to display in the neutral button
     * @param listener The {@link OnClickListener} to use.
     * @return This Builder object to allow for chaining of calls to set methods
     */
    public CWDialog setNeutralButton(int resId, final OnClickListener listener) {
        return setNeutralButton(mContext.getResources().getString(resId), listener, true);
    }

    /**
     * 确认按钮
     *
     * @param resId       按钮提示字符串资料ID
     * @param listener    事件监听
     * @param autoDismiss 是否自动隐藏对话框
     * @return this
     */
    public CWDialog setPositiveButton(int resId, final OnClickListener listener, boolean autoDismiss) {
        return setPositiveButton(mContext.getString(resId), listener, autoDismiss);
    }

    /**
     * 确认按钮
     *
     * @param resId    按钮提示字符串资料ID
     * @param listener 事件监听
     * @return this
     */
    public CWDialog setPositiveButton(int resId, final OnClickListener listener) {
        return setPositiveButton(resId, listener, true);
    }

    /**
     * 设置标题<br />
     * {@inheritDoc}
     */
    public void setTitle(CharSequence title) {
        TextView v = (TextView) contentView.findViewById(CWResource.getId("cw_dialog_title"));
        v.setText(title);
        v.setVisibility(View.VISIBLE);
        showTitleContainer();
    }

    /**
     * 设置标题<br />
     * {@inheritDoc}
     */
    public void setTitle(int resId) {
        TextView v = (TextView) contentView.findViewById(CWResource.getId("cw_dialog_title"));
        v.setText(resId);
        v.setVisibility(View.VISIBLE);
        showTitleContainer();
    }

    public void setTitleAlignLeft(CharSequence title, int leftMargin) {
        TextView v = (TextView) contentView.findViewById(CWResource.getId("cw_dialog_title"));
        v.setText(title);
        v.setVisibility(View.VISIBLE);
        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) v.getLayoutParams();
        params.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
        params.leftMargin = DeviceUtils.dip2px(leftMargin);
        v.setLayoutParams(params);
        showTitleContainer();
    }

    /**
     * 设置标题<br />
     * {@inheritDoc}
     */
    public void setTitleAlignLeft(int resId, int leftMargin) {
        TextView v = (TextView) contentView.findViewById(CWResource.getId("cw_dialog_title"));
        v.setText(resId);
        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) v.getLayoutParams();
        params.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
        params.leftMargin = DeviceUtils.dip2px(leftMargin);
        v.setLayoutParams(params);
        v.setVisibility(View.VISIBLE);
        showTitleContainer();
    }

    private void showTitleContainer() {
        ViewGroup titleContainer = (ViewGroup) contentView.findViewById(CWResource.getId("cw_dialog_title_container"));
        if (titleContainer.getVisibility() != View.VISIBLE) {
            titleContainer.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 设置对话框图标
     *
     * @param icon icon
     * @return this
     */
    public CWDialog setIcon(Drawable icon) {
        ImageView mImageView = (ImageView) contentView.findViewById(CWResource.getId("cw_dialog_icon"));
        mImageView.setImageDrawable(icon);
        mImageView.setVisibility(View.VISIBLE);
        showTitleContainer();
        return this;
    }

    /**
     * 设置对话框图标
     *
     * @param iconResId icon资源id
     * @return this
     */
    public CWDialog setIcon(int iconResId) {
        Drawable mDrawable = mContext.getResources().getDrawable(iconResId);
        setIcon(mDrawable);
        showTitleContainer();
        return this;
    }


    /**
     * 设置主体信息
     *
     * @param msg   信息
     * @param size  大小
     * @param color 颜色
     * @return this
     */
    public CWDialog setMessage(CharSequence msg, int size, int color) {

        final int dipValue = 4;
        TextView mTextView = new TextView(mContext);
        LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,
                LayoutParams.MATCH_PARENT);
        lp.gravity = Gravity.CENTER;
        mTextView.setGravity(Gravity.CENTER);
        mTextView.setTextSize(size);
        if (isTrans) {
            mTextView.setTextColor(Color.WHITE);
        } else {
            mTextView.setTextColor(color);
        }
        mTextView.setPadding(DeviceUtils.dip2px(dipValue), 0,
                DeviceUtils.dip2px(dipValue), DeviceUtils.dip2px(dipValue));
        msg = "\n" + msg + "\n";
        mTextView.setText(msg);
        mTextView.setLineSpacing(0, 1.2f);
        ViewGroup container = (ViewGroup) contentView
                .findViewById(CWResource.getId("cw_dialog_container"));

        container.removeAllViews();
        container.addView(mTextView, lp);
        return this;
    }


    /**
     * 设置主体信息
     *
     * @param msg   信息
     * @param size  大小
     * @param color 颜色
     * @return this
     */
    public CWDialog setMessage(CharSequence msg, int size, int color, int gravity) {

        final int dipValue = 4;
        TextView mTextView = new TextView(mContext);
        LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,
                LayoutParams.MATCH_PARENT);
        lp.gravity = Gravity.CENTER;
        lp.setMargins(20, 0, 20, 0);
        mTextView.setGravity(gravity);
        mTextView.setTextSize(size);
        if (isTrans) {
            mTextView.setTextColor(Color.WHITE);
        } else {
            mTextView.setTextColor(color);
        }
        mTextView.setPadding(DeviceUtils.dip2px(dipValue), 0,
                DeviceUtils.dip2px(dipValue), DeviceUtils.dip2px(dipValue));
        msg = "\n" + msg + "\n";
        mTextView.setText(msg);
        mTextView.setLineSpacing(0, 1.2f);
        ViewGroup container = (ViewGroup) contentView
                .findViewById(CWResource.getId("cw_dialog_container"));

        container.removeAllViews();
        container.addView(mTextView, lp);
        return this;
    }

    /**
     * 设置主体信息
     *
     * @param msg 信息
     * @return this
     */
    public CWDialog setMessage(CharSequence msg) {
        Resources mResources = mContext.getResources();
        setMessage(msg,
                mResources.getInteger(CWResource
                        .getIntegerId("libs_cw_dialog_content_font_size")),
                mResources.getColor(CWResource.getColorId("libs_dialog_content_color")));
        return this;
    }

    public CWDialog setMessagWidePadding(CharSequence msg) {
        Resources mResources = mContext.getResources();
        int size = mResources.getInteger(CWResource.getIntegerId("libs_cw_dialog_content_font_size"));
        final int dipValue = 40;
        final int dipLeftValue = 20;
        TextView mTextView = new TextView(mContext);
        LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,
                LayoutParams.MATCH_PARENT);
        lp.gravity = Gravity.CENTER;
        mTextView.setGravity(Gravity.CENTER);
        mTextView.setTextSize(size);
        mTextView.setMovementMethod(LinkMovementMethod.getInstance());
        mTextView.setPadding(DeviceUtils.dip2px(dipLeftValue), dipValue,
                DeviceUtils.dip2px(dipLeftValue), DeviceUtils.dip2px(dipLeftValue));
//		msg = "\n" + msg + "\n";
        mTextView.setText(msg);
        mTextView.setLineSpacing(0, 1.2f);
        ViewGroup container = (ViewGroup) contentView
                .findViewById(CWResource.getId("cw_dialog_container"));

        container.removeAllViews();
        container.addView(mTextView, lp);
        return this;
    }

    @Override
    public void setContentView(View view) {
        ViewGroup container = (ViewGroup) contentView
                .findViewById(CWResource.getId("cw_dialog_container"));
        container.removeAllViews();
        container.addView(view);
    }

    /**
     * 设置自定义视图
     *
     * @param view   视图
     * @param isFill 是否覆盖原有的视图
     */
    public void setContentView(View view, boolean isFill) {
        if (!isFill) {
            setContentView(view);
        } else {
            super.setContentView(view);
        }
    }

    /**
     * 设置内容视频最小高度
     *
     * @param minHeight 高度
     */
    public void setContentViewMinHeight(int minHeight) {
        ViewGroup container = (ViewGroup) contentView
                .findViewById(CWResource.getId("cw_dialog_container"));
        container.setMinimumHeight(minHeight);
    }

    /**
     * 设置内容视频最小宽度
     *
     * @param minWidth 宽度
     */
    public void setContentViewMinWidth(int minWidth) {
        ViewGroup container = (ViewGroup) contentView
                .findViewById(CWResource.getId("cw_dialog_container"));
        container.setMinimumWidth(minWidth);
    }

    /**
     * 设置标题颜色
     *
     * @param color color
     */
    public void setTitleTextColor(int color) {
        TextView mTextView = (TextView) contentView
                .findViewById(CWResource.getId("cw_dialog_title"));
        mTextView.setTextColor(color);
    }

    /**
     * 设置标题字体大小
     *
     * @param size size
     */
    public void setTitleTextSize(int size) {
        TextView mTextView = (TextView) contentView
                .findViewById(CWResource.getId("cw_dialog_title"));
        mTextView.setTextSize(size);
    }

    /**
     * 设置标题的margin
     *
     * @param left   left
     * @param top    top
     * @param right  right
     * @param bottom bottom
     */
    public void setTitleTextMargin(int left, int top, int right, int bottom) {
        TextView mTextView = (TextView) contentView
                .findViewById(CWResource.getId("cw_dialog_title"));
        LayoutParams lp = (LayoutParams) mTextView.getLayoutParams();
        lp.bottomMargin = bottom;
        lp.leftMargin = left;
        lp.rightMargin = right;
        lp.topMargin = top;
    }

    /**
     * 设置字体
     *
     * @param bold 是否粗体字
     */
    public void setTitleTextBold(boolean bold) {
        TextView mTextView = (TextView) contentView
                .findViewById(CWResource.getId("cw_dialog_title"));
        mTextView.getPaint().setFakeBoldText(true);
    }

    @Override
    public void setContentView(int layoutResID) {
        View view = LayoutInflater.from(mContext).inflate(layoutResID, null);
        setContentView(view);
    }

    /**
     * 设置主体信息
     *
     * @param resId 信息字符串资料id
     * @return this
     */
    public CWDialog setMessage(int resId) {
        setMessage(mContext.getResources().getString(resId));
        return this;
    }

    /**
     * 设置单选列表
     *
     * @param itemsId     数组资源id
     * @param checkedItem 选择项
     * @param listener    项目点击监听事件
     * @return this
     */
    public CWDialog setSingleChoiceItems(int itemsId, int checkedItem,
                                         final OnClickListener listener) {
        CharSequence[] items = mContext.getResources().getStringArray(itemsId);
        setSingleChoiceItems(items, checkedItem, listener);
        return this;
    }

    /**
     * 设置单选列表
     *
     * @param items       资料数组
     * @param checkedItem 选择项
     * @param listener    项目点击监听事件
     * @return this
     */
    public CWDialog setSingleChoiceItems(CharSequence[] items, int checkedItem,
                                         final OnClickListener listener) {

        return setSingleChoiceItems(items, checkedItem, listener, null, null);
    }

    /**
     * 设置单选列表
     *
     * @param items             资料数组
     * @param checkedItem       选择项
     * @param listener          项目点击监听事件
     * @param containerDrawable 容器背景图资源
     * @param selectorDrawable  选择器图资源
     * @return this
     */
    public CWDialog setSingleChoiceItems(CharSequence[] items, int checkedItem,
                                         final OnClickListener listener, Drawable containerDrawable,
                                         Drawable selectorDrawable) {
        if (mListView == null) {
            // Button floor = (Button) contentView.findViewById(CWResource
            // .getId("cw_dialog_button_floor"));
            // floor.setVisibility(View.VISIBLE);
            mListView = (ListView) LayoutInflater.from(mContext)
                    .inflate(CWResource.getLayout("libs_list_view"), null);
            ViewGroup container = (ViewGroup) contentView
                    .findViewById(CWResource.getId("cw_dialog_container"));

            findViewById(CWResource.getId("cw_dialog_top_layout"))
                    .setBackgroundDrawable(
                            (CWResource.getDrawable("tishi_normal")));

            container.addView(mListView);
            final ListAdapter adapter = new ListAdapter(mContext, items);
            mListView.setAdapter(adapter);
            adapter.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
            adapter.setItemChecked(checkedItem, true);
            mListView.setOnItemClickListener(
                    new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent,
                                                View view, int position, long id) {
                            if (listener != null) {
                                listener.onClick(base, position);
                            }
                            adapter.setItemChecked(position, true);
                            adapter.notifyDataSetChanged();
                        }
                    });
            if (selectorDrawable != null) {
                mListView.setSelector(selectorDrawable);
            }
            if (containerDrawable != null) {
                container.setBackgroundDrawable(containerDrawable);
            }
        }

        return this;
    }

    /**
     * 设置单选列表
     *
     * @param items       资料数组
     * @param checkedItem 选择项
     * @param resID       选中效果
     * @param listener    项目点击监听事件
     * @return this
     */
    public CWDialog setSingleChoiceItems(CharSequence[] items, int checkedItem,
                                         int resID, final OnClickListener listener) {
        return setSingleChoiceItems(items, checkedItem, resID, listener, null);
    }

    /**
     * 设置单选列表
     *
     * @param items       资料数组
     * @param checkedItem 选择项
     * @param resID       选中效果
     * @param listener    项目点击监听事件
     * @param drawable    drawable资源
     * @return this
     */
    public CWDialog setSingleChoiceItems(CharSequence[] items, int checkedItem,
                                         int resID, final OnClickListener listener, Drawable drawable) {
        if (mListView == null) {
            mListView = (ListView) LayoutInflater.from(mContext)
                    .inflate(CWResource.getLayout("libs_list_view"), null);
            mListView.setSelector(resID);
            ViewGroup container = (ViewGroup) contentView
                    .findViewById(CWResource.getId("cw_dialog_container"));
            container.addView(mListView);

            final ListAdapter adapter = new ListAdapter(mContext, items);
            mListView.setAdapter(adapter);
            adapter.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
            adapter.setItemChecked(checkedItem, true);
            mListView.setOnItemClickListener(
                    new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent,
                                                View view, int position, long id) {
                            if (listener != null) {
                                listener.onClick(base, position);
                            }
                            adapter.setItemChecked(position, true);
                            adapter.notifyDataSetChanged();
                        }
                    });
            if (drawable != null) {
                contentView
                        .findViewById(
                                CWResource.getId("cw_dialog_content_container"))
                        .setBackgroundDrawable(drawable);
            }
        }
        return this;
    }

    /**
     * 更新对话框中的数据列表
     *
     * @param items       数据源
     * @param checkedItem 选定项
     * @return this
     */
    public CWDialog updateSingleChoiceItems(CharSequence[] items,
                                            int checkedItem) {
        if (mListView != null) {
            ListAdapter adapter = (ListAdapter) mListView.getAdapter();
            adapter.clear();
            for (CharSequence item : items) {
                adapter.add(item);
            }
            adapter.notifyDataSetChanged();
            if (checkedItem >= 0) {
                adapter.setItemChecked(checkedItem, true);
            }
        }
        return this;
    }

    /**
     * 向列表中添加新的数据
     *
     * @param item      要添加的数据
     * @param checkItem 选择id
     * @return this
     */
    public CWDialog addSingleChoiceItem(CharSequence item, int checkItem) {
        updateSingleChoiceItems(new CharSequence[]{item}, checkItem);
        return this;
    }

    /**
     * 向列表中添加新的数据
     *
     * @param item 要添加的数据
     * @return this
     */
    public CWDialog addSingleChoiceItem(CharSequence item) {
        updateSingleChoiceItems(new CharSequence[]{item}, -1);
        return this;
    }

    /**
     * 显示多选项框
     *
     * @param items        数据源
     * @param checkedItems 初始选中的位置
     * @param listener     listener
     * @return CWDialog 对象
     */
    public CWDialog setMultiChoiceItems(CharSequence[] items,
                                        int[] checkedItems, final OnMultiChoiceClickListener listener) {
        if (mListView == null) {
            mListView = (ListView) LayoutInflater.from(mContext)
                    .inflate(CWResource.getLayout("libs_list_view"), null);
            ViewGroup container = (ViewGroup) contentView
                    .findViewById(CWResource.getId("cw_dialog_container"));
            container.addView(mListView);
            final ListAdapter adapter = new ListAdapter(mContext, items);
            mListView.setAdapter(adapter);
            adapter.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
            if (checkedItems != null) {
                final int len = checkedItems.length;
                boolean[] vals = new boolean[len];
                for (int i = 0; i < len; i++) {
                    vals[i] = true;
                }
                adapter.setItemChecked(checkedItems, vals);
            }
            mListView.setOnItemClickListener(
                    new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent,
                                                View view, int position, long id) {
                            if (listener != null) {
                                listener.onClick(base, position, false);
                            }
                            adapter.setItemChecked(position, true);
                            adapter.notifyDataSetChanged();
                        }
                    });
        }
        return this;
    }

    /**
     * 自定义adapter
     *
     * @param adapter  自定义adapter
     * @param listener Dialog点击监听事件
     */
    public void setAdapter(final ListAdapter adapter,
                           final OnClickListener listener) {
        if (mListView == null) {
            mListView = (ListView) LayoutInflater.from(mContext)
                    .inflate(CWResource.getLayout("libs_list_view"), null);
            mListView.setAdapter(adapter);
            if (listener != null) {
                mListView.setOnItemClickListener(
                        new AdapterView.OnItemClickListener() {

                            @Override
                            public void onItemClick(AdapterView<?> parent,
                                                    View view, int position, long id) {
                                listener.onClick(base, position);
                            }

                        });
            }
        }
    }

    /**
     * 自定义adapter
     *
     * @param adapter  自定义adapter
     * @param listener ListView Item点击事件
     */
    public void setAdapter(ListAdapter adapter,
                           AdapterView.OnItemClickListener listener) {
        if (mListView == null) {
            mListView = (ListView) LayoutInflater.from(mContext)
                    .inflate(CWResource.getLayout("libs_list_view"), null);
            mListView.setAdapter(adapter);
            mListView.setOnItemClickListener(listener);
        }
    }

    /**
     * 获取对话框中的ListView
     *
     * @return ListView
     */
    public ListView getListView() {
        return mListView;
    }

    /**
     * 判断单选项是否被选中
     *
     * @param position 选项在listview中的位置
     * @return 是否被选中
     */
    public boolean getSingleChecked(int position) {
        if (mListView != null) {
            ListAdapter adapter = (ListAdapter) mListView.getAdapter();
            return adapter.getSingleChecked(position);
        }
        return false;
    }

    /**
     * 获取单选模式下当前选择项
     *
     * @return 选择项的索引
     */
    public int getSingleCheckedItem() {
        if (mListView != null) {
            ListAdapter adapter = (ListAdapter) mListView.getAdapter();
            return adapter.getSingleCheckedItem();
        }
        return -1;
    }

    /**
     * 判断多选项时，所在位置是否被选中
     *
     * @param position 索引位置
     * @return 该选项是否被选中
     */
    public boolean getMultipleChecked(int position) {
        if (mListView != null) {
            ListAdapter adapter = (ListAdapter) mListView.getAdapter();
            return adapter.getMultipleChecked(position);
        }
        return false;
    }

    @Override
    public void show() {
        super.show();
    }

    /**
     * 内部类<br />
     * dialog中的单选或多选的listview适配器
     *
     * @author PLA-ZJLIU
     */
    private class ListAdapter extends BaseAdapter {

        private List<CharSequence> items;

        private LayoutInflater inflater;

        private int checkedItem = -1;

        private int choiceMode = ListView.CHOICE_MODE_NONE;

        private Map<Integer, Boolean> checkedItems;

        /**
         * 构造函数
         *
         * @param mContext 上下文
         * @param items    数据源
         */
        public ListAdapter(Context mContext, CharSequence[] items) {
            inflater = LayoutInflater.from(mContext);
            this.items = new ArrayList<CharSequence>();
            for (CharSequence item : items) {
                this.items.add(item);
            }
        }

        /**
         * 清除数据
         */
        public void clear() {
            items.clear();
        }

        /**
         * 添加单个数据
         *
         * @param item {@link CharSequence}
         */
        public void add(CharSequence item) {
            items.add(item);
        }

        /**
         * 判断多选项时，所在位置是否被选中
         *
         * @param position 索引位置
         * @return 该选项是否被选中
         */
        public boolean getMultipleChecked(int position) {
            return checkedItems.containsKey(position);
        }

        /**
         * 判断单选项是否被选中
         *
         * @param position 选项在listview中的位置
         * @return 是否被选中
         */
        public boolean getSingleChecked(int position) {
            return position == checkedItem;
        }

        /**
         * 获取当前单选项的位置
         *
         * @return 选项位置
         */
        public int getSingleCheckedItem() {
            return checkedItem;
        }

        /**
         * 设置单选或多选模式
         *
         * @param mode ListView.MODE <br />
         *             {@link ListView.CHOICE_MODE_NONE} <br />
         *             {@link ListView.CHOICE_MODE_MULTIPLE} <br />
         *             {@link ListView.CHOICE_MODE_SINGLE} <br />
         */
        public void setChoiceMode(int mode) {
            choiceMode = mode;
        }

        @Override
        public int getCount() {
            return items == null ? 0 : items.size();
        }

        @Override
        public Object getItem(int position) {
            return items == null ? null : items.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        /**
         * 设置选择项
         *
         * @param item    选择项索引
         * @param checked 选择状态(true or false)
         */
        public void setItemChecked(int item, boolean checked) {
            if (choiceMode == ListView.CHOICE_MODE_NONE) {
                return;
            }
            if (choiceMode == ListView.CHOICE_MODE_SINGLE) {
                this.checkedItem = item;
            } else if (choiceMode == ListView.CHOICE_MODE_MULTIPLE) {
                if (this.checkedItems == null) {
                    this.checkedItems = new HashMap<Integer, Boolean>();
                }
                if (this.checkedItems.containsKey(item)) {
                    this.checkedItems.remove(item);
                } else {
                    if (checked) {
                        this.checkedItems.put(item, true);
                    }
                }
            }
            notifyDataSetChanged();
        }

        /**
         * 设置复选框的选定状态
         *
         * @param items 需要更改选择状态的索引数组
         * @param vals  对应的值
         */
        public void setItemChecked(int[] indexs, boolean[] vals) {
            if (choiceMode == ListView.CHOICE_MODE_MULTIPLE) {
                if (this.checkedItems == null) {
                    this.checkedItems = new HashMap<Integer, Boolean>();
                }
                final int len = indexs.length;
                for (int i = 0; i < len; i++) {
                    final boolean checked = vals[i];
                    final int checkeditem = indexs[i];
                    if (this.checkedItems.containsKey(checkedItem)) {
                        if (!checked) {
                            this.checkedItems.remove(checkedItem);
                        }
                    } else {
                        if (checked) {
                            this.checkedItems.put(checkedItem, true);
                        }
                    }
                }
                notifyDataSetChanged();
            }
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                if (choiceMode == ListView.CHOICE_MODE_SINGLE) {
                    convertView = inflater.inflate(
                            CWResource.getLayout("libs_single_checked_text"),
                            null);
                } else if (choiceMode == ListView.CHOICE_MODE_MULTIPLE) {
                    convertView = inflater.inflate(
                            CWResource.getLayout("libs_multiple_checked_text"),
                            null);
                } else {
                    convertView = inflater
                            .inflate(android.R.layout.simple_list_item_1, null);
                }
                holder = new ViewHolder();
                if (choiceMode == ListView.CHOICE_MODE_NONE) {
                    holder.mTextView = (TextView) convertView
                            .findViewById(android.R.id.text1);
                } else {
                    holder.checkedTextView = (CheckedTextView) convertView
                            .findViewById(android.R.id.text1);
                }
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            if (choiceMode == ListView.CHOICE_MODE_NONE) {
                holder.mTextView.setText(items.get(position));
            } else {
                holder.checkedTextView.setText(items.get(position));
                if (choiceMode == ListView.CHOICE_MODE_SINGLE) {
                    if (checkedItem == position) {
                        holder.checkedTextView.setChecked(true);
                    } else {
                        holder.checkedTextView.setChecked(false);
                    }
                }
                if (choiceMode == ListView.CHOICE_MODE_MULTIPLE) {
                    if (checkedItems != null
                            && checkedItems.containsKey(position)) {
                        holder.checkedTextView.setChecked(true);
                    } else {
                        holder.checkedTextView.setChecked(false);
                    }
                }
            }
            return convertView;
        }

        /**
         * 辅助静态类
         *
         * @author PLA-ZJLIU
         */
        class ViewHolder {
            private CheckedTextView checkedTextView;

            private TextView mTextView;
        }
    }

    public void showFromBottom() {
        Window dialogWindow = getWindow();
        dialogWindow.setGravity(Gravity.BOTTOM);
        WindowManager.LayoutParams attributes = dialogWindow.getAttributes();
        attributes.width = LayoutParams.MATCH_PARENT;
        dialogWindow.setWindowAnimations(
                CWResource.getStyles("BottomDialogMenuAnim")); // 添加动画
        super.show();
    }

    public void showFromCenter() {
        Window dialogWindow = getWindow();
        dialogWindow.setGravity(Gravity.CENTER);
        WindowManager.LayoutParams attributes = dialogWindow.getAttributes();
        attributes.width = LayoutParams.MATCH_PARENT;
        dialogWindow.setWindowAnimations(
                CWResource.getStyles("BottomDialogMenuAnim")); // 添加动画
        super.show();
    }

}
